<template>
  <input type="text" v-model="user.id">
  <input type="text" v-model="user.name">
  <button @click="addItem">提交</button>
  <ul>
    <li v-for="(item, i) in data.arr" :key="item.id" @click="removeItem(i)">{{ item.name }}</li>
  </ul>
</template>

<script>
import { reactive } from 'vue'
export default {
  setup() {
    // !reactive 可以普通对象包装成响应式的对象
    const data = reactive({
      arr: [
        {
          id: 0,
          name: 'ifer',
        },
        {
          id: 1,
          name: 'elser',
        },
        {
          id: 2,
          name: 'xxx',
        },
      ],
    })

    const removeItem = (i) => {
      data.arr.splice(i, 1)
    }
    // !#1 收集数据用的，和 input 框双向绑定
    const user = reactive({
      id: '',
      name: ''
    })

    // !#2 添加 user 到 data.arr
    const addItem = () => {
      // 下面写法错误，会相互影响
      // data.arr.push(user)

      /* data.arr.push({
        id: user.id,
        name: user.name
      }) */
      // 推荐写法
      data.arr.push({
        ...user
      })

      user.id = ''
      user.name = ''
      // data.arr.push(Object.assign({}, user))
    }
    return { data, removeItem, user, addItem }
  }
}
</script>